﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Go;

public class FogGo
{
	public static int none = 0;
	public static int black = 1;
	public static int white = 2;
	public static int fog = 10;

	int[,] board_state;
	int size;
	public Player self;
	public GameState curGameState;

	public bool IsOver { get { return curGameState.is_over(); } }
	public bool IsSelfTurn { get { return curGameState.next_player == self; } }

	public FogGo(int size, Player self)
	{
		this.size = size;
		this.self = self;
		board_state = new int[size + 1, size + 1];
		curGameState = GameState.new_game(size);
		ClearBoardState();
	}

	void ClearBoardState()
	{
		for (int i = 1; i <= size; i++)
		{
			for (int j = 1; j <= size; j++)
			{
				board_state[i, j] = none + fog;
			}
		}
	}

	public void UpdateBoardState()
	{
		ClearBoardState();
		for (int i = 1; i <= size; i++)
		{
			for (int j = 1; j <= size; j++)
			{
				Point point = new Point(i, j);
				Player stone = curGameState.board.get(point);
				if (stone == Player.black) board_state[i, j] += black;
				if (stone == Player.white) board_state[i, j] += white;
				if (stone == self)
				{
					// clear fog
					if (board_state[i, j] >= fog) board_state[i, j] -= fog;
					var neighbors = point.sight();
					foreach (Point neighbor in neighbors)
					{
						if (curGameState.board.is_on_grid(neighbor))
						{
							if (board_state[neighbor.row, neighbor.col] >= fog) board_state[neighbor.row, neighbor.col] -= fog;
						}
					}
				}
			}
		}
	}

	public bool CanTakeMove(Point point)
	{
		if (curGameState.is_over()) return false; // 棋局已结束
		if (curGameState.next_player != self) return false; // 不是自己的回合，点啥都没用
		if (!curGameState.board.is_on_grid(point)) return false; // 超出棋盘范围

		int point_state = board_state[point.row, point.col];
		if (point_state < fog && point_state != none) return false; // 看得见的有子的地方肯定不能下
		return true;
		//if (point_state >= fog)
		//{
		//	if (point_state - fog > 0) return true; // 看不见的地方有子也能下
		//	if (curGameState.is_valid_move(new Move(point))) return true; // 看不见的地方除禁手外都能下
		//}
		//return curGameState.is_valid_move(new Move(point));
	}

	/// <summary>
	/// 进行行动
	/// </summary>
	/// <param name="move"></param>
	public void TakeMove(Move move)
	{
		if (curGameState.is_valid_move(move))
		{
			curGameState = curGameState.apply_move(move);
			if (move.is_play) UpdateBoardState();
		}
		else
		{
			// 进行了无用手
			curGameState = new GameState(curGameState.board, curGameState.next_player.other(), curGameState, new Move(Point.None));
		}
	}

	public Player GetColor(int row, int col)
	{
		int point_state = board_state[row, col] % fog;
		if (point_state == black) return Player.black;
		if (point_state == white) return Player.white;
		return Player.none;
	}

	public bool IsVisiable(int row, int col)
	{
		return board_state[row, col] < fog;
	}
}
